package com.liuyk.commonlib.update;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import androidx.core.app.NotificationCompat;

import com.liuyk.commonlib.R;

/**
 * 通知栏进度
 * <p>
 * Created by liuyakui on 2020-02-14.
 */
public class UpdateNotifyManager {
    private static final int PROGRESS_ID = 1002;
    private static UpdateNotifyManager INSTANCE;
    private NotificationManager notificationManager;
    private Notification notification; //下载通知进度提示
    private NotificationCompat.Builder builder;

    //根据version name可以找到apk文件
    private String mVersionName;
    //重试
    private String mApkUrl;

    private UpdateNotifyManager(Context context) {
        initNotification(context);
    }

    public synchronized static UpdateNotifyManager getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new UpdateNotifyManager(context);
        }
        return INSTANCE;
    }

    //初始化通知
    private void initNotification(Context context) {
        try {
            notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            builder = new NotificationCompat.Builder(context);
            builder.setContentTitle("正在下载...") //设置通知标题
                    .setSmallIcon(R.mipmap.update_apk_icon)
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.update_apk_icon)) //设置通知的大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS) //设置通知的提醒方式： 呼吸灯
                    .setPriority(NotificationCompat.PRIORITY_MAX) //设置通知的优先级：最大
                    .setOnlyAlertOnce(true)
                    .setSound(null)
                    .setVibrate(new long[]{0})//关闭震动
                    .setAutoCancel(false)//设置通知被点击一次是否自动取消
                    .setContentText("下载进度:" + "0%")
                    .setProgress(100, 0, false);

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel("002", "download_channel002", NotificationManager.IMPORTANCE_DEFAULT);
                notificationManager.createNotificationChannel(channel);
                builder.setChannelId("002");
            }

            notification = builder.build();//构建通知对象
            notification.flags = Notification.FLAG_NO_CLEAR;//不可以清楚
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void show() {
        try {
            notification = builder.build();
            notificationManager.notify(PROGRESS_ID, notification);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void notifyChanger() {
        try {
            notification = builder.build();
            notificationManager.notify(PROGRESS_ID, notification);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //icon title如果不设置，会用默认的，如果需要设置，必须在notify之前设置
    public void setContentTitle(String title) {
        builder.setContentTitle(title);
    }

    public void setSmallIcon(int resId) {
        builder.setSmallIcon(resId);
    }

    public void setLargeIcon(Bitmap bitmap) {
        builder.setLargeIcon(bitmap);
    }

    public void updateProgress(String apkUrl, String versionName, float length, float progress) {
        mVersionName = versionName;
        mApkUrl = apkUrl;
        try {
            builder.setProgress((int) length, (int) progress, false);
            if (length <= 0) {
                length = 100;
            }
            int percent = (int) (progress / length * 100f);
            builder.setContentText("下载进度:" + percent + "%");
            notifyChanger();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //在一些特定情况下，更新通知栏内容，例如：下载失败，安装失败等
    public void updateNotify(String apkUrl, String versionName, String msg) {
        mVersionName = versionName;
        mApkUrl = apkUrl;
        try {
            builder.setContentText(msg);
            notifyChanger();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void clickRetry(Context context) {
        Intent intentClick = new Intent(context, DownBroadcastReceiver.class);
        intentClick.setAction(DownBroadcastReceiver.RETRY_ACTION);
        intentClick.putExtra("versionName", mVersionName);
        intentClick.putExtra("apkUrl", mApkUrl);
        PendingIntent pendingIntentClick = PendingIntent.getBroadcast(
                context, 0, intentClick, PendingIntent.FLAG_ONE_SHOT);
        builder.setContentIntent(pendingIntentClick);
        notification = builder.build();
        notificationManager.notify(PROGRESS_ID, notification);
    }

    //安装
    public void clickInstall(Context context) {
        Intent intentClick = new Intent(context, DownBroadcastReceiver.class);
        intentClick.setAction(DownBroadcastReceiver.INSTALL_ACTION);
        intentClick.putExtra("versionName", mVersionName);
        intentClick.putExtra("apkUrl", mApkUrl);
        PendingIntent pendingIntentClick = PendingIntent.getBroadcast(
                context, 0, intentClick, PendingIntent.FLAG_ONE_SHOT);
        builder.setContentIntent(pendingIntentClick);
        notification = builder.build();
        notificationManager.notify(PROGRESS_ID, notification);
    }

    public void cancel() {
        try {
            notificationManager.cancel(PROGRESS_ID);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
